package calin.podcast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.view.Menu;

public class Podcasts extends Application {
	private MediaPlayer mPlayer;
	public static final Boolean DEBUG = true;
	private CalinPodcastSettingsDbAdapter mSettingsDbHelper;
	private CalinDatabaseHelper dbHelper;
	public static final int CONFIG_ID = Menu.FIRST;
	public static final int ABOUTUS_ID = Menu.FIRST + 1;
	public static final int ACTIVITY_SETTINGS = 0;
	public static final int ACTIVITY_ABOUTUS = 1;
	public static final int ACTIVITY_SETTINGS_BROWSER = 2;
	private static final String SETTINGS_NAME = "settings";
	private static final String DEFAULT_PODCASTS_DIR = "podcasts";
	private String DEFAULT_PODCASTS_PATH;
	private File nextItem;
	static {
        System.loadLibrary("calin-jni");
        System.loadLibrary("calin-test");
        System.loadLibrary("calin-listfiles");
    }
	
	public native String  stringFromJNI();
	
	public native String  stringPassJNI(String test);
	
	public native String[]  listFiles(String Path);

	public String getDefaultPath() {
		DEFAULT_PODCASTS_PATH = getDir(DEFAULT_PODCASTS_DIR,
				MODE_WORLD_WRITEABLE).getAbsolutePath();

		File podcasts = new File("/sdcard/podcasts");
		podcasts.mkdir();
		
		return "/sdcard/podcasts";
		//return DEFAULT_PODCASTS_PATH;
	}

	public String getCustomPath(Activity mActivity) {
		return getSettings("podcasts_path", mActivity);
	}

	public File getPodcastDirectory(Activity mActivity) {
		File podcastDirectory = new File(getDefaultPath());

		File customPodcastDirectory = new File(getCustomPath(mActivity));
		if (customPodcastDirectory.exists())
			podcastDirectory = customPodcastDirectory;

		return podcastDirectory;
	}

	public File getDirectory(String path) {
		File directory = null;
		try{
			if(path == null) directory = new File(getDefaultPath());
			else directory = new File(path);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return directory;
	}

	public void initSettings() {
		mSettingsDbHelper = new CalinPodcastSettingsDbAdapter(this);
		mSettingsDbHelper.open();
	}
	
	public String getAppDir(){
		String appDir = null;
		try {
			PackageManager packageManager = getPackageManager();
			String packageName = getPackageName();
			PackageInfo packageInfo;
			packageInfo = packageManager.getPackageInfo(packageName, 0);
			appDir = packageInfo.applicationInfo.dataDir;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return appDir;
	}

	public String getSettings(String key, Activity mActivity) {
		initSettings();
		Cursor mCursor = mSettingsDbHelper.fetchItem(key);
		mActivity.startManagingCursor(mCursor);
		String value = mCursor.getString(mCursor.getColumnIndexOrThrow(CalinPodcastSettingsDbAdapter.KEY_VALUE));
		return value;
	}

	public void setSettings(String key, String value, Activity mActivity) {
		initSettings();
		Cursor mCursor = mSettingsDbHelper.fetchItem(key);
		mActivity.startManagingCursor(mCursor);
		if(mCursor.equals(null)) mSettingsDbHelper.addItem(key, value);
		else mSettingsDbHelper.updateItem(key, value);
	}
	
	public File getNextPlayItem(File item){
		File directory = new File(item.getParent());
		File[] files = directory.listFiles();
		for (int i = 0; i < files.length; i++) {
			if(item.equals(files[i])&&i<files.length-1) return files[i+1];
		}
		
		return null;
	}

	public void play(File item) {
		try {
			String path = item.getAbsolutePath();
			nextItem = getNextPlayItem(item);

			if (path == "")
				return;

			if (mPlayer != null) {
				mPlayer.release();
				mPlayer = null;
			}
			mPlayer = new MediaPlayer();
			mPlayer.setDataSource(path);
			mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
				public void onCompletion(MediaPlayer mp) {
					mp.stop();
					mp.release();
					play(nextItem);
				}
			});
			mPlayer.prepare();
			mPlayer.start();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
	}

	public void setSettingsString(String key, String value) {
		SharedPreferences sharedPreferences = getSharedPreferences(
				SETTINGS_NAME, Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();

		editor.putString(key, value);
		editor.commit();
	}

	public void setSettingsInt(String key, int value) {
		SharedPreferences sharedPreferences = getSharedPreferences(
				SETTINGS_NAME, Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();

		editor.putInt(key, value);
		editor.commit();
	}

	public void setSettingsLong(String key, long value) {
		SharedPreferences sharedPreferences = getSharedPreferences(
				SETTINGS_NAME, Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();

		editor.putLong(key, value);
		editor.commit();
	}

	public void setSettingsFloat(String key, float value) {
		SharedPreferences sharedPreferences = getSharedPreferences(
				SETTINGS_NAME, Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();

		editor.putFloat(key, value);
		editor.commit();
	}

	public void setSettingsBoolean(String key, boolean value) {
		SharedPreferences sharedPreferences = getSharedPreferences(
				SETTINGS_NAME, Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();

		editor.putBoolean(key, value);
		editor.commit();
	}

	public String getSettingsString(String key) {
		SharedPreferences sharedPreferences = getSharedPreferences(
				SETTINGS_NAME, Context.MODE_PRIVATE);

		return sharedPreferences.getString(key, null);
	}

	public int getSettingsInt(String key) {
		SharedPreferences sharedPreferences = getSharedPreferences(
				SETTINGS_NAME, Context.MODE_PRIVATE);

		return sharedPreferences.getInt(key, 0);
	}

	public long getSettingsLong(String key) {
		SharedPreferences sharedPreferences = getSharedPreferences(
				SETTINGS_NAME, Context.MODE_PRIVATE);

		return sharedPreferences.getLong(key, 0);
	}

	public float getSettingsFloat(String key) {
		SharedPreferences sharedPreferences = getSharedPreferences(
				SETTINGS_NAME, Context.MODE_PRIVATE);

		return sharedPreferences.getFloat(key, 0);
	}

	public boolean getSettingsBoolean(String key) {
		SharedPreferences sharedPreferences = getSharedPreferences(
				SETTINGS_NAME, Context.MODE_PRIVATE);

		return sharedPreferences.getBoolean(key, false);
	}

	public String getSettingsPath() {
		return getFilesDir().getAbsolutePath() + "/../shared_prefs/"
				+ SETTINGS_NAME + ".xml";
	}

	public Boolean checkSettingsFile() {
		File file = new File(getSettingsPath());

		return file.exists();

	}

	public void setDefaultSettings() {
		InputStream inputStream = null;
		try {
			SharedPreferences sharedPreferences = getSharedPreferences(
					SETTINGS_NAME, Context.MODE_PRIVATE);
			Editor editor = sharedPreferences.edit();
			editor.commit();
			inputStream = getResources().openRawResource(R.raw.settings);
			int size = inputStream.available();

			byte[] buffer = new byte[size];
			inputStream.read(buffer);
			inputStream.close();
			FileOutputStream fos = new FileOutputStream(getSettingsPath());
			fos.write(buffer);
			fos.flush();
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void debug(Exception e) {
		//Log.d("Calin Podcast", " Exception error: " + e.toString());
	}
}
